<script setup lang="ts">
import { delEnterpriseAPI,  getBuildingListAPI,  getEnterpriseListAPI, UploadAPI } from '@/apis/enterprise';
import { addRentAPI, delRentAPI, getRentListAPI, outRentAPI } from '@/apis/rent';
import type { BuildItem,  Enterprise, EnterpriseListParams } from '@/types/enterprise';
import type { addRentParams, houseContract } from '@/types/rent';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules,  type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { ref, watch } from 'vue';

// 前端自定义的类型,用于展示嵌套表格
interface EnterpriseWithRent extends Enterprise{
  // 合同列表
  RentList: houseContract[]
}

const EnterpriseParams = ref<EnterpriseListParams>({
  page: 1,
  pageSize: 5,
  name: '',
})

const EnterpriseList = ref<Enterprise[]>([])
const total = ref(0)

const getEnterpriseList = async () => {
  const res = await getEnterpriseListAPI(EnterpriseParams.value)
  // console.log(res)
  EnterpriseList.value = res.data.rows
  total.value = res.data.total
}
getEnterpriseList()

// 查询企业
const onsubmit = () => {
  EnterpriseParams.value.page = 1
  getEnterpriseList()
}
// 删除企业
const delexpreise = (id: string) => {
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await delEnterpriseAPI(id)
    ElMessage.success('删除成功')
    getEnterpriseList()
  })
}


// 合同表单
const params = ref<EnterpriseListParams>({
  name: '',
  page: 1,
  pageSize: 5,
})

// 添加合同

const addRentParams = ref<addRentParams>({
  buildingId: undefined, //租赁楼宇
  contractId: undefined, //合同id
  contractUrl: '',// 合同url
  startTime:'', //租赁开始日期
  endTime: '', //租赁截止日期
  enterpriseId: undefined, //企业id
  type: 0 //操作类型，添加合同0，续签合同1
})



const rentDialogVisible = ref(false)
const BuildList = ref<BuildItem[]>([])

const addRent = async (id: number) => {
  console.log(id)
  // 打开弹窗
  rentDialogVisible.value = true
  // 获取可租赁楼宇列表
  const res = await getBuildingListAPI(params.value)
  // console.log(res)
  BuildList.value = res.data.rows
  // 保存企业id
  addRentParams.value.enterpriseId = id
}

const fileList = ref<UploadUserFile[]>([])
const addRentRef = ref<FormInstance>()
// 关闭合同弹窗
const CloseRent = () => {
  // 关闭弹窗
  rentDialogVisible.value = false
  // 重置表单
  addRentRef.value?.resetFields()
  // 重置日期
  dateArr.value = []
  // 重置文件列表(前端)
  fileList.value = []
  // 重置提交给后端的表单数据(后端)
  addRentParams.value = {
    buildingId: undefined, //租赁楼宇
    contractId: undefined, //合同id
    contractUrl: '',// 合同url
    startTime:'', //租赁开始日期
    endTime: '', //租赁截止日期
    enterpriseId: undefined, //企业id
    type: 0 //操作类型，添加合同0，续签合同1
  }
}


// 侦听日期变化
const dateArr = ref<string[]>([])
watch(dateArr, () => {
  if (dateArr.value) {
    addRentParams.value.startTime = dateArr.value[0]
    addRentParams.value.endTime = dateArr.value[1]
  } else {
    addRentParams.value.startTime = ''
    addRentParams.value.endTime = ''
  }
}, { deep: true })

// 禁用日期
const disabledDate = (time: Date) => {
  // // 禁用今天之前的日期
  return time.getTime() < Date.now() - 1000 * 60 * 60 * 24 
}

const addRentRules = ref<FormRules<addRentParams>>({
  buildingId: [
    { required: true, message: '请选择租赁楼宇', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择租赁截止日期', trigger: 'change' }
  ],
  contractId: [
    { required: true, message: '请上传租赁合同', trigger: 'change' }
  ]
})

// 上传合同文件
const UpLoadHttpRequest = async (options:UploadRequestOptions) => {
  // console.log(options)
  const fd = new FormData()
  fd.append('file', options.file)
  fd.append('type', 'contract')
  // 上传文件,发送请求
  const res = await UploadAPI(fd)
  // console.log(res)
  // 保存合同附件 url 和 id,用于添加合同
  addRentParams.value.contractUrl = res.data.url
  addRentParams.value.contractId = res.data.id
  // 主动触发校验
  addRentRef.value?.validateField('contractId')
  return res.data
}

const removeUpload = () => {
  addRentParams.value.contractUrl = ''
  addRentParams.value.contractId = undefined
  addRentRef.value?.validateField('contractId')
}

const beforeUpload = (rawFile:UploadRawFile) => {
  // 允许文件的大小
  const allowSize = 5 * 1024 * 1024
  // 检测文件大小
  if (rawFile.size > allowSize) {
    ElMessage.error('文件过大,请上传5M一下的文件')
    return false
  }
  return true
}

// 添加合同
const addRentConfirm = async () => {
  try {
    // 总体校验
    await addRentRef.value?.validate()
    // 添加合同
    await addRentAPI(addRentParams.value)
    // 轻提示
    ElMessage.success('添加成功')
    // 关闭弹窗
    rentDialogVisible.value = false
    
  } catch {
    
  }
}

// 展开行时触发
const onExpandChange = async (row: EnterpriseWithRent) => {
  // 获取该企业租赁列表
  const res = await getRentListAPI(row.id)
  console.log(res)
  row.RentList = res.data
}

// 退租合同
const outRent = (row: houseContract) => {
  ElMessageBox.confirm('退租不可撤回,是否确认退租当前楼宇?, 是否继续?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 发送请求,更新后端合同状态
    await outRentAPI(row.id)
    // 更新前端合同状态,后端合同状态
    row.status = 3
    // 轻提示
    ElMessage.success('退租成功')
  })
}

// 删除企业租赁合同(合同Row,企业Row)
const deleteRent = (rentRow: houseContract, enterpriseRow: EnterpriseWithRent) => {
  console.log(rentRow, enterpriseRow)
  ElMessageBox.confirm('是否确认删除当前合同?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 发送请求,删除后端合同
    await delRentAPI(rentRow.id)
    // 删除过滤合同(前端)
    enterpriseRow.RentList = enterpriseRow.RentList.filter(item => item.id !== rentRow.id)
    // 轻提示
    ElMessage.success('删除成功')
  }).catch(() => {
    
  })
}
</script>


<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input clearable placeholder="请输入内容" class="search-main" v-model="EnterpriseParams.name" @keyup.enter="getEnterpriseList()" @clear="onsubmit()"/>
      <el-button type="primary" @click="onsubmit()">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/exterpriseAdd')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="EnterpriseList" @expand-change="onExpandChange" row-key="id">
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-table :data="row.RentList">
              <el-table-column label="租赁楼宇" prop="buildingName"></el-table-column>
              <el-table-column label="租赁起始时间" prop="startTime"></el-table-column>
              <el-table-column label="合同状态" prop="status">
                <template v-slot="{ row }">
                  <el-tag v-if="row.status === 0" type="warning">待生效</el-tag>
                  <el-tag v-else-if="row.status === 1" type="success">生效中</el-tag>
                  <el-tag v-else-if="row.status === 2" type="info">已到期</el-tag>
                  <el-tag v-else-if="row.status === 3" type="danger">已退租</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="{ row:rentRow }">
                  <el-button size="small" type="primary">续租</el-button>
                  <el-button size="small" type="primary" @click="outRent(rentRow)" :disabled="rentRow.status === 3">退租</el-button>
                  <el-button size="small" type="primary" :disabled="rentRow.status !== 3" @click="deleteRent(rentRow,row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="120" prop="id"/>
        <el-table-column label="企业名称" width="320" prop="name"/>
        <el-table-column label="联系人" prop="contact"/>
        <el-table-column label="联系电话" prop="contactNumber"/>
        <el-table-column label="操作">
          <template #default="scoped">
            <el-button size="small" type="primary" @click="addRent(scoped.row.id)">添加合同</el-button>
            <el-button size="small" type="primary" @click="$router.push(`/watchEnterprise/${scoped.row.id}`)">查看</el-button>
            <el-button size="small" type="primary" @click="$router.push(`/exterpriseAdd/${scoped.row.id}`)">编辑</el-button>
            <el-button size="small" type="primary" @click="delexpreise(scoped.row.id)">删除</el-button>
            <el-button size="small" type="primary" @click="$router.push(`/exterpriseDetail/${scoped.row.id}`)">查看租赁合同</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
     <el-pagination
      :page-sizes="[2, 5, 10, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      v-model:current-page="EnterpriseParams.page"
      v-model:page-size="EnterpriseParams.pageSize"
      @change="getEnterpriseList"
      :total="total"
      style="margin-top: 5px;"
      />
    </div>
      <el-dialog v-model="rentDialogVisible" width="580px" @close="CloseRent">
        <div class="form-container"> 
          <!-- 表单区域 -->
            <el-form label-position="top" :model="addRentParams" ref="addRentRef" :rules="addRentRules">
            <el-form-item label="租赁楼宇" prop="buildingId">
              <el-select placeholder="请选择" v-model="addRentParams.buildingId">
                <el-option v-for="item in BuildList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="租赁起止日期" prop="endTime">
              <el-date-picker 
              type="daterange" 
              range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="YYYY-MM-DD" 
              v-model="dateArr"
              />
            </el-form-item>
            <el-form-item label="租赁合同" prop="contractId">
              <el-upload 
              accept=".doc, .pdf"
              :http-request="UpLoadHttpRequest"
              @remove="removeUpload"
              :before-upload="beforeUpload"
              v-model:file-list="fileList"
              :disabled-date="disabledDate"
              >
                <el-button size="small" type="primary" plain>上传合同文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
          {{ addRentParams }}
          {{ fileList }}
        </div>
        <template #footer>
          <el-button @click="CloseRent">取消</el-button>
          <el-button @click="addRentConfirm" type="primary">确定</el-button>
        </template>
  </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>